package cn.e2win.biz.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import cn.e2win.base.entity.SysFunction;
import cn.e2win.biz.util.StringUtils;


//1 加载资源与权限的对应关系  
public class DmsSecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {
	static Log logger = LogFactory.getLog(DmsSecurityMetadataSource.class);

	private FunctionDao functionDao;

	private static Map<String, Collection<ConfigAttribute>> functionMap = null;

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}

	// 加载所有资源与权限的关系
	private void loadResourceDefine() {
		if (functionMap == null) {
			functionMap = new HashMap<String, Collection<ConfigAttribute>>();
			List<SysFunction> resources = this.functionDao.readAll();
			for (SysFunction resource : resources) {
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				// 以权限名封装为Spring的security Object
				ConfigAttribute configAttribute = new SecurityConfig(
						resource.getTitle());
				configAttributes.add(configAttribute);
				functionMap.put(simpleUrl(resource.getUrl()), configAttributes);
			}
		}
		//
		// Set<Entry<String, Collection<ConfigAttribute>>> resourceSet =
		// functionMap.entrySet();
		// Iterator<Entry<String, Collection<ConfigAttribute>>> iterator =
		// resourceSet.iterator();

	}

	// 返回所请求资源所需要的权限
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {

		String requestUrl = ((FilterInvocation) object).getRequestUrl();
		logger.info("requestUrl is " + requestUrl);
		if (functionMap == null) {
			loadResourceDefine();
		}
		return functionMap.get(simpleUrl(requestUrl));
	}
	
	public FunctionDao getFunctionDao() {
		return functionDao;
	}

	public void setFunctionDao(FunctionDao functionDao) {
		this.functionDao = functionDao;
	}

	private String simpleUrl(String url) {
		if(!StringUtils.isEmpty(url)){
			String[] temp = url.split("/");
			return "/" + temp[1];
		}
		return "";
	}


}
